$(function () {
    // 接口文档：
    // url： getAllCategories.php
    // 返回值：
    //  { 
    //   code：代表请求的状态
    //   msg：返回的信息
    //   data：（数组）请求返回的分类信息
    //  }

    // 请求分类数据
    $.ajax({
        type: 'post',
        url: '/admin/api/getAllCategories.php',
        dataType: 'json',
        success: function (res) {
            // 数据渲染
            if (res.code == 1) {
                $('tbody').html(template('categoryTp', res.data));
            }
        }
    });


    // 把600+个图标放到点击图标显示的div里面(这是一个体力活，懒得打。嘿嘿~~)
    (function () {
        var iconsArr = [
            "fa-glass",
            "fa-music", "fa-search", "fa-envelope-o", "fa-heart", "fa-star", "fa-star-o", "fa-user", "fa-film", "fa-th-large", "fa-th", "fa-th-list", "fa-check", "fa-times", "fa-search-plus", "fa-search-minus", "fa-power-off", "fa-signal", "fa-cog", "fa-trash-o", "fa-home", "fa-file-o", "fa-clock-o", "fa-road", "fa-download", "fa-arrow-circle-o-down", "fa-arrow-circle-o-up", "fa-inbox", "fa-play-circle-o", "fa-repeat", "fa-refresh", "fa-list-alt", "fa-lock", "fa-flag", "fa-headphones", "fa-volume-off", "fa-volume-down", "fa-volume-up", "fa-qrcode", "fa-barcode", "fa-tag", "fa-tags", "fa-book", "fa-bookmark", "fa-print", "fa-camera", "fa-font", "fa-bold", "fa-italic", "fa-text-height", "fa-text-width", "fa-align-left", "fa-align-center", "fa-align-right", "fa-align-justify", "fa-list", "fa-outdent", "fa-indent", "fa-video-camera", "fa-picture-o", "fa-pencil", "fa-map-marker", "fa-adjust", "fa-tint", "fa-pencil-square-o", "fa-share-square-o", "fa-check-square-o", "fa-arrows", "fa-step-backward", "fa-fast-backward", "fa-backward", "fa-play", "fa-pause", "fa-stop", "fa-forward", "fa-fast-forward", "fa-step-forward", "fa-eject", "fa-chevron-left", "fa-chevron-right", "fa-plus-circle", "fa-minus-circle", "fa-times-circle", "fa-check-circle", "fa-question-circle", "fa-info-circle", "fa-crosshairs", "fa-times-circle-o", "fa-check-circle-o", "fa-ban", "fa-arrow-left", "fa-arrow-right", "fa-arrow-up", "fa-arrow-down", "fa-share", "fa-expand", "fa-compress", "fa-plus", "fa-minus", "fa-asterisk", "fa-exclamation-circle", "fa-gift", "fa-leaf", "fa-fire", "fa-eye", "fa-eye-slash", "fa-exclamation-triangle", "fa-plane", "fa-calendar", "fa-random", "fa-comment", "fa-magnet", "fa-chevron-up", "fa-chevron-down", "fa-retweet", "fa-shopping-cart", "fa-folder", "fa-folder-open", "fa-arrows-v", "fa-arrows-h", "fa-bar-chart", "fa-twitter-square", "fa-facebook-square", "fa-camera-retro", "fa-key", "fa-cogs", "fa-comments", "fa-thumbs-o-up", "fa-thumbs-o-down", "fa-star-half", "fa-heart-o", "fa-sign-out", "fa-linkedin-square", "fa-thumb-tack", "fa-external-link", "fa-sign-in", "fa-trophy", "fa-github-square", "fa-upload", "fa-lemon-o", "fa-phone", "fa-square-o", "fa-bookmark-o", "fa-phone-square", "fa-twitter", "fa-facebook", "fa-github", "fa-unlock", "fa-credit-card", "fa-rss", "fa-hdd-o", "fa-bullhorn", "fa-bell", "fa-certificate", "fa-hand-o-right", "fa-hand-o-left", "fa-hand-o-up", "fa-hand-o-down", "fa-arrow-circle-left", "fa-arrow-circle-right", "fa-arrow-circle-up", "fa-arrow-circle-down", "fa-globe", "fa-wrench", "fa-tasks", "fa-filter", "fa-briefcase", "fa-arrows-alt", "fa-users", "fa-link", "fa-cloud", "fa-flask", "fa-scissors", "fa-files-o", "fa-paperclip", "fa-floppy-o", "fa-square", "fa-bars", "fa-list-ul", "fa-list-ol", "fa-strikethrough", "fa-underline", "fa-table", "fa-magic", "fa-truck", "fa-pinterest", "fa-pinterest-square", "fa-google-plus-square", "fa-google-plus", "fa-money", "fa-caret-down", "fa-caret-up", "fa-caret-left", "fa-caret-right", "fa-columns", "fa-sort", "fa-sort-desc", "fa-sort-asc", "fa-envelope", "fa-linkedin", "fa-undo", "fa-gavel", "fa-tachometer", "fa-comment-o", "fa-comments-o", "fa-bolt", "fa-sitemap", "fa-umbrella", "fa-clipboard", "fa-lightbulb-o", "fa-exchange", "fa-cloud-download", "fa-cloud-upload", "fa-user-md", "fa-stethoscope", "fa-suitcase", "fa-bell-o", "fa-coffee", "fa-cutlery", "fa-file-text-o", "fa-building-o", "fa-hospital-o", "fa-ambulance", "fa-medkit", "fa-fighter-jet", "fa-beer", "fa-h-square", "fa-plus-square", "fa-angle-double-left", "fa-angle-double-right", "fa-angle-double-up", "fa-angle-double-down", "fa-angle-left", "fa-angle-right", "fa-angle-up", "fa-angle-down", "fa-desktop", "fa-laptop", "fa-tablet", "fa-mobile", "fa-circle-o", "fa-quote-left", "fa-quote-right", "fa-spinner", "fa-circle", "fa-reply", "fa-github-alt", "fa-folder-o", "fa-folder-open-o", "fa-smile-o", "fa-frown-o", "fa-meh-o", "fa-gamepad", "fa-keyboard-o", "fa-flag-o", "fa-flag-checkered", "fa-terminal", "fa-code", "fa-reply-all", "fa-star-half-o", "fa-location-arrow", "fa-crop", "fa-code-fork", "fa-chain-broken", "fa-question", "fa-info", "fa-exclamation", "fa-superscript", "fa-subscript", "fa-eraser", "fa-puzzle-piece", "fa-microphone", "fa-microphone-slash", "fa-shield", "fa-calendar-o", "fa-fire-extinguisher", "fa-rocket", "fa-maxcdn", "fa-chevron-circle-left", "fa-chevron-circle-right", "fa-chevron-circle-up", "fa-chevron-circle-down", "fa-html5", "fa-css3", "fa-anchor", "fa-unlock-alt", "fa-bullseye", "fa-ellipsis-h", "fa-ellipsis-v", "fa-rss-square", "fa-play-circle", "fa-ticket", "fa-minus-square", "fa-minus-square-o", "fa-level-up", "fa-level-down", "fa-check-square", "fa-pencil-square", "fa-external-link-square", "fa-share-square", "fa-compass", "fa-caret-square-o-down", "fa-caret-square-o-up", "fa-caret-square-o-right", "fa-eur", "fa-gbp", "fa-usd", "fa-inr", "fa-jpy", "fa-rub", "fa-krw", "fa-btc", "fa-file", "fa-file-text", "fa-sort-alpha-asc", "fa-sort-alpha-desc", "fa-sort-amount-asc", "fa-sort-amount-desc", "fa-sort-numeric-asc", "fa-sort-numeric-desc", "fa-thumbs-up", "fa-thumbs-down", "fa-youtube-square", "fa-youtube", "fa-xing", "fa-xing-square", "fa-youtube-play", "fa-dropbox", "fa-stack-overflow", "fa-instagram", "fa-flickr", "fa-adn", "fa-bitbucket", "fa-bitbucket-square", "fa-tumblr", "fa-tumblr-square", "fa-long-arrow-down", "fa-long-arrow-up", "fa-long-arrow-left", "fa-long-arrow-right", "fa-apple", "fa-windows", "fa-android", "fa-linux", "fa-dribbble", "fa-skype", "fa-foursquare", "fa-trello", "fa-female", "fa-male", "fa-gratipay", "fa-sun-o", "fa-moon-o", "fa-archive", "fa-bug", "fa-vk", "fa-weibo", "fa-renren", "fa-pagelines", "fa-stack-exchange", "fa-arrow-circle-o-right", "fa-arrow-circle-o-left", "fa-caret-square-o-left", "fa-dot-circle-o", "fa-wheelchair", "fa-vimeo-square", "fa-try", "fa-plus-square-o", "fa-space-shuttle", "fa-slack", "fa-envelope-square", "fa-wordpress", "fa-openid", "fa-university", "fa-graduation-cap", "fa-yahoo", "fa-google", "fa-reddit", "fa-reddit-square", "fa-stumbleupon-circle", "fa-stumbleupon", "fa-delicious", "fa-digg", "fa-pied-piper-pp", "fa-pied-piper-alt", "fa-drupal", "fa-joomla", "fa-language", "fa-fax", "fa-building", "fa-child", "fa-paw", "fa-spoon", "fa-cube", "fa-cubes", "fa-behance", "fa-behance-square", "fa-steam", "fa-steam-square", "fa-recycle", "fa-car", "fa-taxi", "fa-tree", "fa-spotify", "fa-deviantart", "fa-soundcloud", "fa-database", "fa-file-pdf-o", "fa-file-word-o", "fa-file-excel-o", "fa-file-powerpoint-o", "fa-file-image-o", "fa-file-archive-o", "fa-file-audio-o", "fa-file-video-o", "fa-file-code-o", "fa-vine", "fa-codepen", "fa-jsfiddle", "fa-life-ring", "fa-circle-o-notch", "fa-rebel", "fa-empire", "fa-git-square", "fa-git", "fa-hacker-news", "fa-tencent-weibo", "fa-qq", "fa-weixin", "fa-paper-plane", "fa-paper-plane-o", "fa-history", "fa-circle-thin", "fa-header", "fa-paragraph", "fa-sliders", "fa-share-alt", "fa-share-alt-square", "fa-bomb", "fa-futbol-o", "fa-tty", "fa-binoculars", "fa-plug", "fa-slideshare", "fa-twitch", "fa-yelp", "fa-newspaper-o", "fa-wifi", "fa-calculator", "fa-paypal", "fa-google-wallet", "fa-cc-visa", "fa-cc-mastercard", "fa-cc-discover", "fa-cc-amex", "fa-cc-paypal", "fa-cc-stripe", "fa-bell-slash", "fa-bell-slash-o", "fa-trash", "fa-copyright", "fa-at", "fa-eyedropper", "fa-paint-brush", "fa-birthday-cake", "fa-area-chart", "fa-pie-chart", "fa-line-chart", "fa-lastfm", "fa-lastfm-square", "fa-toggle-off", "fa-toggle-on", "fa-bicycle", "fa-bus", "fa-ioxhost", "fa-angellist", "fa-cc", "fa-ils", "fa-meanpath", "fa-buysellads", "fa-connectdevelop", "fa-dashcube", "fa-forumbee", "fa-leanpub", "fa-sellsy", "fa-shirtsinbulk", "fa-simplybuilt", "fa-skyatlas", "fa-cart-plus", "fa-cart-arrow-down", "fa-diamond", "fa-ship", "fa-user-secret", "fa-motorcycle", "fa-street-view", "fa-heartbeat", "fa-venus", "fa-mars", "fa-mercury", "fa-transgender", "fa-transgender-alt", "fa-venus-double", "fa-mars-double", "fa-venus-mars", "fa-mars-stroke", "fa-mars-stroke-v", "fa-mars-stroke-h", "fa-neuter", "fa-genderless", "fa-facebook-official", "fa-pinterest-p", "fa-whatsapp", "fa-server", "fa-user-plus", "fa-user-times", "fa-bed", "fa-viacoin", "fa-train", "fa-subway", "fa-medium", "fa-y-combinator", "fa-optin-monster", "fa-opencart", "fa-expeditedssl", "fa-battery-full", "fa-battery-three-quarters", "fa-battery-half", "fa-battery-quarter", "fa-battery-empty", "fa-mouse-pointer", "fa-i-cursor", "fa-object-group", "fa-object-ungroup", "fa-sticky-note", "fa-sticky-note-o", "fa-cc-jcb", "fa-cc-diners-club", "fa-clone", "fa-balance-scale", "fa-hourglass-o", "fa-hourglass-start", "fa-hourglass-half", "fa-hourglass-end", "fa-hourglass", "fa-hand-rock-o", "fa-hand-paper-o", "fa-hand-scissors-o", "fa-hand-lizard-o", "fa-hand-spock-o", "fa-hand-pointer-o", "fa-hand-peace-o", "fa-trademark", "fa-registered", "fa-creative-commons", "fa-gg", "fa-gg-circle", "fa-tripadvisor", "fa-odnoklassniki", "fa-odnoklassniki-square", "fa-get-pocket", "fa-wikipedia-w", "fa-safari", "fa-chrome", "fa-firefox", "fa-opera", "fa-internet-explorer", "fa-television", "fa-contao", "fa-500px", "fa-amazon", "fa-calendar-plus-o", "fa-calendar-minus-o", "fa-calendar-times-o", "fa-calendar-check-o", "fa-industry", "fa-map-pin", "fa-map-signs", "fa-map-o", "fa-map", "fa-commenting", "fa-commenting-o", "fa-houzz", "fa-vimeo", "fa-black-tie", "fa-fonticons", "fa-reddit-alien", "fa-edge", "fa-credit-card-alt", "fa-codiepie", "fa-modx", "fa-fort-awesome", "fa-usb", "fa-product-hunt", "fa-mixcloud", "fa-scribd", "fa-pause-circle", "fa-pause-circle-o", "fa-stop-circle", "fa-stop-circle-o", "fa-shopping-bag", "fa-shopping-basket", "fa-hashtag", "fa-bluetooth", "fa-bluetooth-b", "fa-percent", "fa-gitlab", "fa-wpbeginner", "fa-wpforms", "fa-envira", "fa-universal-access", "fa-wheelchair-alt", "fa-question-circle-o", "fa-blind", "fa-audio-description", "fa-volume-control-phone", "fa-braille", "fa-assistive-listening-systems", "fa-american-sign-language-interpreting", "fa-deaf", "fa-glide", "fa-glide-g", "fa-sign-language", "fa-low-vision", "fa-viadeo", "fa-viadeo-square", "fa-snapchat", "fa-snapchat-ghost", "fa-snapchat-square", "fa-pied-piper", "fa-first-order", "fa-yoast", "fa-themeisle", "fa-google-plus-official", "fa-font-awesome", "fa-handshake-o", "fa-envelope-open", "fa-envelope-open-o", "fa-linode", "fa-address-book", "fa-address-book-o", "fa-address-card", "fa-address-card-o", "fa-user-circle", "fa-user-circle-o", "fa-user-o", "fa-id-badge", "fa-id-card", "fa-id-card-o", "fa-quora", "fa-free-code-camp", "fa-telegram", "fa-thermometer-full", "fa-thermometer-three-quarters", "fa-thermometer-half", "fa-thermometer-quarter", "fa-thermometer-empty", "fa-shower", "fa-bath", "fa-podcast", "fa-window-maximize", "fa-window-minimize", "fa-window-restore", "fa-window-close", "fa-window-close-o", "fa-bandcamp", "fa-grav", "fa-etsy", "fa-imdb", "fa-ravelry", "fa-eercast", "fa-microchip", "fa-snowflake-o", "fa-superpowers", "fa-wpexplorer", "fa-meetup"];
    
    // 遍历数组，把所有的图标放到div里面
        var html = [];
        for (var i = 0; i < iconsArr.length; i++ ){
            html.push('<span class="fa ' + iconsArr[i] + '"></span>');
        }
    
    // 把所有的图标放到icons-inner div里面
        $('.icons-inner').html(html.join(''));
    })();

    // 点击图标的时候，把所有的图标显示出来
    $('.icons').on('click', function () {
        // 显示所有的图标
        $('.icons-contain').show();
    });

    // 在点击隐藏小图标的时候，要把小图标的class放给点击切换的按钮
    $('.icons-inner > span').on('click', function () {
        // 把当前点击的图标的class，设置给之前点击的class
        var cn = $(this).attr('class');
        $('.icons > span').attr('class', cn);
        
        // 还要把class同步到隐藏域
        $('#classname').val(cn.substring(3));
        // 把已经打开的选择图标窗口关闭
        $('.icons-contain').fadeOut(1);
    });
    
    // 点击关闭
    $('.closeBut').on('click', function () {
        
        $('.icons-contain').fadeOut(1);
    });

    // 新增数据
    // 给添加按钮注册点击事件
    $('#add').on('click', function () {
    //    收集数据，进行验证
        var name = $('#name').val();
        var slug = $('#slug').val();

        // 非空验证
        if (name.trim() == "") {
            // 警告用户
            $('.alert').removeClass('hidden').children('.msg').text('请填写分类的名称');
            setTimeout(function () {
                $('.alert').addClass('hidden');
            }, 1000);
            return;
        }
        if (slug.trim() == "") {
            // 警告用户
            $('.alert').removeClass('hidden').children('.msg').text('请填写分类的别名');
            setTimeout(function () {
                $('.alert').addClass('hidden');

            }, 1000);
            return;
        }


        // 把三个数据收集起来，发送到服务端，请求添加
        var data = $('#form').serialize();
        // 使用ajax请求吧数据发送到服务端
        $.ajax({
            type: 'post',
            url: '/admin/api/addNewCategory.php',
            data: data,
            dataType:'json',
            success: function (res) {
                console.log(res);
                if (res.code == 1 ) {
                    alert(res.msg);
                    location.reload();
                }
            }
        });
    });
    

    // 点击编辑按钮 但是动态生成的元素 一般都用委托的方式注册事件
    // $(动态生成元素的前代元素).on(事件类型，动态元素的选择器，回调函数);

    $('tbody').on('click', '.edit', function () {
        // 把当前要编辑的内容，放到左边的表单里面
        // 先找到tr
        var tr = $(this).parent().parent();
        // tr的第2个格子就是name
        var name = tr.children().eq(1).text();

        // 把name放到第一个输入框
        $('#name').val(name);
        var slug = tr.children().eq(2).text();
        $('#slug').val(slug);
        
        // 把图标同步   把图标的class获取过来
        var className = tr.children().eq(3).children().attr('class');

        $('.icons > span').attr('class', className);
        
        // 把隐藏域的图标同步
        $('#classname').val(className.substring(3));

        // 把id存到表单里面的某个隐藏域
        // 这个隐藏域一开始是不存在的，需要在点击编辑的时候动态的创建
        var id = tr.attr('categoryid');
        var idElement = $("<input type='hidden' name='id' value='" + id + "'>");
        // 在最前面的元素追加元素
        $('#form').prepend(idElement);

        // 把保存按钮和取消按钮显示，把添加按钮隐藏
        $('.saves').show();
        $('#add').hide();
    });

    // 点击取消
    $('#cancle').on('click', function () {
    //    让表单恢复默认
        $('#name').val('');
        $('#slug').val('');
        $('.icons > span').attr('class', 'fa fa-glass');
        
        // 把隐藏域的图标同步
        $('#classname').val('fa-glass');
        
        // 把id的隐藏域去掉
        $('#form').children().eq(0).remove();

        // 把添加显示，把保存和取消隐藏
        $('.saves').hide();
        $('#add').show();
    });


    // 保存按钮
    $('#save').on('click', function () {
        // 收集数据，进行验证
        var name = $('#name').val();
        var slug = $('#slug').val();
        // 非空验证
        if (name.trim() == "") {
            // 警告用户
            $('.alert').removeClass('hidden').children('.msg').text('请填写分类的名称');
            setTimeout(function () {
                $('.alert').addClass('hidden');
            }, 1000);
            return;
        }
        if (slug.trim() == "") {
            // 警告用户
            $('.alert').removeClass('hidden').children('.msg').text('请填写分类的别名');
            setTimeout(function() {
                $('.alert').addClass('hidden');
            }, 1000);
            return;
        }

        var data = $('#form').serialize();

        // 收集数据，发送请求
        $.ajax({
            type:'post',
            url: '/admin/api/updateCategoryById.php',
            data:data,
            dataType:'json',
            success: function (res) { 
                if (res.code) {
                    alert(res.msg);
                    location.reload();
                }
            }
        });
    });


    // 删除数据
    // 删除按钮注册点击事件
    $('tbody').on('click', '.del', function () {
        // 根据id，发送请求到服务端，删除数据
        // 1.获取id
        var id = $(this).parent().parent().attr('categoryid');
        // 2.发送请求
        if (confirm('你确定要删除这条数据吗？')) {
            // 3.ajax请求
            $.ajax({
                type: "post",
                url: "/admin/api/delCategoryByid.php",
                data: { id },
                dataType: "json",
                success: function (res) {
                    console.log(res);
                    if (res.code == 1) { 
                        alert(res.msg);
                        // 以前一直都是使用重新加载的方式刷新数据，一般在市面上除了使用刷新的方式，还可以直接把这个数据从页面上移除的方式，当用户量和数据量比较大，一般使用DOM操作移除，当数据的时效性要求比较高，使用刷新
                        location.reload();
                    }
                }
            });
        }
    });

    // 全选和反选功能
    $('#ckall').on('click', function () {
        // 把tobody里面的所有的多选框都控制跟当前的状态一致
        // 获取当前自己的选中状态
        // prop这个方法管理开关属性
        var status = $(this).prop('checked');
        $('tbody input').prop('checked', status);
        // 判断是否全选，如果是全选，就让批量删除按钮显示
        if (status) {
            $('#delAll').show();
        } else {
            $("#delAll").hide();
        }
    });


    // tbody里面的所有的多选框注册点击事件
    $('tbody').on('click', 'input', function () {
        // 判断是否全都选中
        // 如果选中的元素的个数 == 所有的元素的个数
        // size()方法，返回jq对象中的dom元素的个数
        $('#ckall').prop('checked', $('tbody input:checked').size() == $('tbody input').size());

        // 当选中的个数 > 1的时候，把批量删除显示，否则隐藏
        if ($('tbody input:checked').size() > 1) {
            $('#delAll').show();
        } else { 
            $('#delAll').hide();
        }
    });

    // 批量删除
    $('#delAll').on('click', function () {
        // 确认操作
        if (!confirm('确定要删除所选择的数据吗？')) {
            return;
        }
        // 收集选中的行的分类id
        var idArr = [];

        // 找到所有被选中的多选框
        var cks = $('tbody input:checked');
        
        // 遍历cks伪数组，获取每个id
        cks.each(function (i, e) {
            // i表示的是索引
            // e表示的是标签
            var tr = $(e).parent().parent();
            // 获取id
            var id = tr.attr('categoryid');
            // 把id存到数组里面
            idArr.push(id);
        });

        // 把要删除的id发送给服务端
        $.ajax({
            type: "post",
            url: "/admin/api/delLotCategory.php",
            data: {idArr:idArr},
            dataType: "json",
            success: function (res) {
                console.log(res);
                if (res.code == 1 ) {
                    alert(res.msg);
                    location.reload();
                }
            }
        });
    });
});
